//
//  SelectView.m
//  SelectControl
//
//  Created by Summer on 15/12/23.
//  Copyright © 2015年 Summer. All rights reserved.
//

#define MARGIN 8.0f
#define SCREEN_W [UIScreen mainScreen].bounds.size.width
#define SCREEN_H [UIScreen mainScreen].bounds.size.height

#import "SelectView.h"
#import "SelectItem.h"
#import "OptionModel.h"

@interface SelectView()

/** 所有答案控件 **/
@property(nonatomic, strong) NSMutableArray * itemControls;

/** 选中的item **/
@property(nonatomic, weak) SelectItem * selectedItem;

@end

@implementation SelectView

#pragma mark - - 根据模型初始化自控件
- (void)setOptionModels:(NSArray *)optionModels{
    _optionModels = optionModels;
    
    // 根据模型创建Items
    [self initControls];
    
    // 设置Items位置
    [self setControlFrames];
}

#pragma mark - - 控件创建

/** 初始化子控件 **/
- (void) initControls{
    
    for (OptionModel * model in self.optionModels) {
        // 创建item
        [self.itemControls addObject:[self createItemWithModel:model]];
    }
}

/** 创建一个Item **/
- (SelectItem *)createItemWithModel:(OptionModel *)model{
    
    SelectItem * item = [[SelectItem alloc] init];
    
    item.backgroundColor = [UIColor grayColor];
    
    item.optionModel = model;
    
    [item addTarget:self action:@selector(clickItem:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:item];
    
    return item;
}
 
#pragma mark - - 控件位置计算
- (void)layoutSubviews{
    [super layoutSubviews];
    [self setControlFrames];
}

/** 设置子控件位置 **/
- (void)setControlFrames{
    
    CGFloat itemW = (SCREEN_W - MARGIN * 3) * 0.45;
    CGFloat itemH = (self.frame.size.height - MARGIN) * 0.45;
    
    for (int i = 0; i < self.itemControls.count; i++) {
        
        SelectItem * item = [self.itemControls objectAtIndex:i];
        
        CGFloat row = i / 2;
        CGFloat line = i % 2;
        
        CGFloat itemX = MARGIN + (MARGIN + itemW) * line +10;
        CGFloat itemY = (MARGIN + itemH) * row +5;

        item.frame = CGRectMake(itemX, itemY, itemW, itemH);
        
    }
}

#pragma mark - - 控件逻辑
- (void)clickItem:(SelectItem *)item{
    self.selectedItem = item;
    if (self.selectItemCall) { self.selectItemCall(item.optionModel); }
}

/** 设置选中状态 **/
- (void)setSelectedItem:(SelectItem *)selectedItem{
    [self deSelectedItem];
    _selectedItem = selectedItem;
    selectedItem.itemSelected = YES;
}

/** 取消选中状态 **/
- (void)deSelectedItem{
    _selectedItem.itemSelected = NO;
    _selectedItem = nil;
}

#pragma mark - - 辅助方法
- (void)cancelSelected{
    [self deSelectedItem];
}

/** 当前选中的Item **/
- (SelectItem *)currentSelectItem{
    return self.selectedItem;
}

#pragma mark - - 懒加载
- (NSMutableArray *)itemControls{
    if (!_itemControls){
        _itemControls = [NSMutableArray array];
    }
    return _itemControls;
}

@end
